<template>
  <div class="statistics-container">
    <h1 class="page-title">景点数据统计分析</h1>

    <!-- 数据概览卡片 -->
    <div class="data-overview">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-card class="data-card total-spots">
            <div class="card-content">
              <div class="card-icon">
                <el-icon>
                  <Location />
                </el-icon>
              </div>
              <div class="card-info">
                <div class="card-value">{{ totalSpots }}</div>
                <div class="card-label">景点总数</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="8">
          <el-card class="data-card total-visits">
            <div class="card-content">
              <div class="card-icon">
                <el-icon>
                  <View />
                </el-icon>
              </div>
              <div class="card-info">
                <div class="card-value">{{ totalVisits }}</div>
                <div class="card-label">总访问量</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="8">
          <el-card class="data-card avg-rating">
            <div class="card-content">
              <div class="card-icon">
                <el-icon>
                  <Star />
                </el-icon>
              </div>
              <div class="card-info">
                <div class="card-value">{{ avgRating }}</div>
                <div class="card-label">平均评分</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 图表区域 -->
    <div class="chart-section">
      <el-row :gutter="20">
        <!-- 景点类型分布 -->
        <el-col :span="12">
          <el-card class="chart-card">
            <template #header>
              <div class="card-header">
                <span>景点类型分布</span>
                <el-tooltip content="展示不同类型景点的数量分布" placement="top">
                  <el-icon>
                    <InfoFilled />
                  </el-icon>
                </el-tooltip>
              </div>
            </template>
            <div class="chart-container" ref="spotTypeChartRef"></div>
          </el-card>
        </el-col>

        <!-- 访问量趋势 -->
        <el-col :span="12">
          <el-card class="chart-card">
            <template #header>
              <div class="card-header">
                <span>访问量趋势</span>
                <el-tooltip content="展示近期景点访问量变化趋势" placement="top">
                  <el-icon>
                    <InfoFilled />
                  </el-icon>
                </el-tooltip>
              </div>
            </template>
            <div class="chart-container" ref="visitsChartRef"></div>
          </el-card>
        </el-col>
      </el-row>

      <el-row :gutter="20" class="second-row">
        <!-- 热门景点排行 -->
        <el-col :span="12">
          <el-card class="chart-card">
            <template #header>
              <div class="card-header">
                <span>热门景点排行</span>
                <el-tooltip content="按访问量排序的热门景点" placement="top">
                  <el-icon>
                    <InfoFilled />
                  </el-icon>
                </el-tooltip>
              </div>
            </template>
            <div class="chart-container" ref="popularSpotsChartRef"></div>
          </el-card>
        </el-col>

        <!-- 用户评价分析 -->
        <el-col :span="12">
          <el-card class="chart-card">
            <template #header>
              <div class="card-header">
                <span>用户评价分析</span>
                <el-tooltip content="各评分段的评论数量分布" placement="top">
                  <el-icon>
                    <InfoFilled />
                  </el-icon>
                </el-tooltip>
              </div>
            </template>
            <div class="chart-container" ref="ratingChartRef"></div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 景点详细数据表格 -->
    <el-card class="data-table-card">
      <template #header>
        <div class="card-header">
          <span>景点详细数据</span>
          <div class="header-actions">
            <el-input v-model="searchKeyword" placeholder="搜索景点" prefix-icon="Search" clearable class="search-input" />
            <el-select v-model="filterType" placeholder="类型筛选" clearable class="filter-select">
              <el-option v-for="type in attractionTypes" :key="type.value" :label="type.label" :value="type.value" />
            </el-select>
          </div>
        </div>
      </template>

      <el-table :data="filteredTableData" stripe style="width: 100%" :max-height="400">
        <el-table-column prop="name" label="景点名称" min-width="120" />
        <el-table-column prop="type" label="类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getTagType(row.type)">
              {{ getTypeLabel(row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="visits" label="访问量" width="90" sortable />
        <el-table-column prop="commentCount" label="评论数" width="90" sortable />
        <el-table-column prop="rating" label="评分" width="100" sortable>
          <template #default="{ row }">
            <div class="rating-display">
              <el-rate v-model="row.rating" disabled text-color="#ff9900" />
              <span>{{ row.rating > 0 ? row.rating : '暂无' }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="lastUpdate" label="最后更新" width="180" sortable />
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="viewSpotDetails(row.id)">
              <el-icon>
                <View />
              </el-icon> 查看
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper" :total="totalItems" @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed, watch } from 'vue'
import { Location, View, Star, InfoFilled, Search } from '@element-plus/icons-vue'
import * as echarts from 'echarts'
import FeatureLayer from '@arcgis/core/layers/FeatureLayer'

// 数据统计
const totalSpots = ref(0)
const totalVisits = ref(0)
const avgRating = ref(0)

// 图表引用
const spotTypeChartRef = ref<HTMLElement | null>(null)
const visitsChartRef = ref<HTMLElement | null>(null)
const popularSpotsChartRef = ref<HTMLElement | null>(null)
const ratingChartRef = ref<HTMLElement | null>(null)

// 图表实例
let spotTypeChart: echarts.ECharts | null = null
let visitsChart: echarts.ECharts | null = null
let popularSpotsChart: echarts.ECharts | null = null
let ratingChart: echarts.ECharts | null = null

// 表格数据
interface ScenicSpot {
  id: number;
  name: string;
  type: string;
  description: string;
  visits: number;
  rating: number;
  lastUpdate: string;
  UserJsonData: any;
}

const tableData = ref<ScenicSpot[]>([]);
const searchKeyword = ref('')
const filterType = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const totalItems = ref(0)

// 景点类型
const attractionTypes = [
  { value: 'natural', label: '自然风光' },
  { value: 'historical', label: '历史文化' },
  { value: 'entertainment', label: '休闲娱乐' },
]

// 获取类型标签
const getTypeLabel = (value: string) => {
  const type = attractionTypes.find((t) => t.value === value)
  return type ? type.label : value
}

// 获取标签类型
const getTagType = (type: string) => {
  const typeMap: Record<string, string> = {
    natural: 'success',
    historical: 'danger',
    entertainment: 'primary',
  }
  return typeMap[type] || 'info'
}

// 筛选表格数据
const filteredTableData = computed(() => {
  let data = [...tableData.value]

  // 关键词搜索
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    data = data.filter((item) => item.name.toLowerCase().includes(keyword))
  }

  // 类型筛选
  if (filterType.value) {
    data = data.filter((item) => item.type === filterType.value)
  }

  // 将计算总数的逻辑移到computed外部
  const updateTotalItems = (data: { name: string; type: string; visits: number; rating: number; lastUpdate: string }[]) => {
    totalItems.value = data.length
  }
  updateTotalItems(data)

  // 分页
  const startIndex = (currentPage.value - 1) * pageSize.value
  return data.slice(startIndex, startIndex + pageSize.value)
})

// 分页处理
const handleSizeChange = (val: number) => {
  pageSize.value = val
  currentPage.value = 1
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
}

// 查看景点详情
const viewSpotDetails = (id: number) => {
  console.log('查看景点详情:', id)
  // 实现查看详情的逻辑
}

// 初始化景点类型分布图表
const initSpotTypeChart = () => {
  if (!spotTypeChartRef.value) return

  spotTypeChart = echarts.init(spotTypeChartRef.value)

  // 统计各类型景点数量和评论数
  const typeStats = {
    natural: { count: 0, comments: 0, rating: 0 },
    historical: { count: 0, comments: 0, rating: 0 },
    entertainment: { count: 0, comments: 0, rating: 0 },
  }

  tableData.value.forEach((item) => {
    if (typeStats.hasOwnProperty(item.type)) {
      const type = item.type as keyof typeof typeStats
      typeStats[type].count++
      typeStats[type].comments += item.commentCount || 0

      // 累加评分（只计算有评分的景点）
      if (item.rating > 0) {
        typeStats[type].rating += item.rating
      }
    }
  })

  // 计算各类型的平均评分
  Object.keys(typeStats).forEach(type => {
    const typeStat = typeStats[type as keyof typeof typeStats]
    if (typeStat.comments > 0) {
      typeStat.rating = parseFloat((typeStat.rating / typeStat.comments).toFixed(1))
    }
  })

  const option = {
    tooltip: {
      trigger: 'item',
      formatter: function (params) {
        const type = params.data.type
        const stats = typeStats[type]
        return `${params.name}<br/>
               景点数量: ${stats.count}个<br/>
               评论总数: ${stats.comments}条<br/>
               平均评分: ${stats.rating || '暂无'}`
      }
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      data: attractionTypes.map((type) => type.label),
    },
    series: [
      {
        name: '景点类型',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2,
        },
        label: {
          show: false,
          position: 'center',
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 16,
            fontWeight: 'bold',
          },
        },
        labelLine: {
          show: false,
        },
        data: [
          {
            value: typeStats.natural.count,
            name: '自然风光',
            type: 'natural',
            itemStyle: { color: '#67C23A' },
          },
          {
            value: typeStats.historical.count,
            name: '历史文化',
            type: 'historical',
            itemStyle: { color: '#F56C6C' },
          },
          {
            value: typeStats.entertainment.count,
            name: '休闲娱乐',
            type: 'entertainment',
            itemStyle: { color: '#409EFF' },
          },
        ],
      },
    ],
  }

  spotTypeChart.setOption(option)
}

// 初始化访问量趋势图表（按景点类型统计）
const initVisitsChart = () => {
  if (!visitsChartRef.value) return

  visitsChart = echarts.init(visitsChartRef.value)

  // 按景点类型统计访问量和评论数
  const typeStats = {
    historical: { visits: 0, comments: 0, spots: 0 },
    natural: { visits: 0, comments: 0, spots: 0 },
    entertainment: { visits: 0, comments: 0, spots: 0 }
  }

  // 统计各类型景点的访问量和评论数
  tableData.value.forEach(spot => {
    if (typeStats[spot.type]) {
      typeStats[spot.type].visits += spot.visits
      typeStats[spot.type].comments += spot.commentCount || 0
      typeStats[spot.type].spots += 1
    }
  })

  // 准备图表数据
  const types = Object.keys(typeStats)
  const typeLabels = types.map(type => getTypeLabel(type))
  const visitData = types.map(type => typeStats[type as keyof typeof typeStats].visits)
  const commentData = types.map(type => typeStats[type].comments)

  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      formatter: function (params) {
        const typeIndex = params[0].dataIndex
        const type = types[typeIndex]
        return `${getTypeLabel(type)}<br/>
               景点数量: ${typeStats[type].spots}个<br/>
               访问量: ${typeStats[type].visits}<br/>
               评论数: ${typeStats[type].comments}`
      }
    },
    legend: {
      data: ['访问量', '评论数']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: [
      {
        type: 'category',
        data: typeLabels,
        axisTick: {
          alignWithLabel: true
        }
      }
    ],
    yAxis: [
      {
        type: 'value',
        name: '数量',
        position: 'left'
      }
    ],
    series: [
      {
        name: '访问量',
        type: 'bar',
        barWidth: '40%',
        data: visitData.map((value, index) => ({
          value,
          itemStyle: {
            color: getBarColor(types[index])
          }
        }))
      },
      {
        name: '评论数',
        type: 'line',
        smooth: true,
        data: commentData,
        itemStyle: {
          color: '#E6A23C'
        },
        lineStyle: {
          width: 3
        },
        symbol: 'circle',
        symbolSize: 8
      }
    ]
  }

  visitsChart.setOption(option)
}

// 初始化热门景点排行图表
const initPopularSpotsChart = () => {
  if (!popularSpotsChartRef.value) return

  popularSpotsChart = echarts.init(popularSpotsChartRef.value)

  // 按访问量排序并获取前10个景点（只包含有评论的景点）
  const sortedData = [...tableData.value]
    .filter(item => item.commentCount > 0) // 只显示有评论的景点
    .sort((a, b) => b.visits - a.visits)
    .slice(0, 10)

  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow',
      },
      formatter: function (params) {
        const item = params[0];
        return `${item.name}<br/>${item.seriesName}: ${item.value}<br/>评论数: ${sortedData[item.dataIndex].commentCount}`;
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true,
    },
    xAxis: {
      type: 'value',
      name: '访问量',
    },
    yAxis: {
      type: 'category',
      data: sortedData.map((item) => item.name),
      axisLabel: {
        width: 100,
        overflow: 'truncate',
        interval: 0,
      },
    },
    series: [
      {
        name: '访问量',
        type: 'bar',
        data: sortedData.map((item) => ({
          value: item.visits,
          itemStyle: {
            color: getBarColor(item.type),
          },
        })),
      },
    ],
  }

  popularSpotsChart.setOption(option)
}

// 根据类型获取柱状图颜色
const getBarColor = (type: string) => {
  const colorMap: Record<string, string> = {
    natural: '#67C23A',
    historical: '#F56C6C',
    entertainment: '#409EFF',
  }
  return colorMap[type] || '#909399'
}

// 初始化评分分析图表
const initRatingChart = () => {
  if (!ratingChartRef.value) return

  ratingChart = echarts.init(ratingChartRef.value)

  // 统计各评分段的评论数量（而不是景点数量）
  const ratingDistribution = [0, 0, 0, 0, 0] // 对应1-5星
  const spotCountByRating = [0, 0, 0, 0, 0] // 每个评分段的景点数量
  const totalCommentsByRating = [0, 0, 0, 0, 0] // 每个评分段的总评论数
  console.log(tableData.value)
  // 遍历所有景点，解析UserJsonData获取评论数据
  tableData.value.forEach((spot) => {
    if (spot.commentCount > 0 && spot.rating > 0) {
      console.log(spot.UserJsonData)
      try {
        // 直接使用spot中的UserJsonData
        if (spot.UserJsonData) {
          const userData = JSON.parse(spot.UserJsonData)
          if (userData.comments && userData.comments.length > 0) {
            // 统计每条评论的评分分布
            userData.comments.forEach((comment) => {
              // 确保评分在1-5之间
              const rating = comment.rating || 0
              console.log(rating)
              const ratingIndex = rating - 1
              ratingDistribution[ratingIndex]++
              totalCommentsByRating[ratingIndex]++
            })
          }
        } else {
          console.error('UserJsonData is undefined for spot:', spot)
          // 如果没有UserJsonData，使用处理后的数据
          const ratingIndex = Math.floor(spot.rating) - 1
          if (ratingIndex >= 0 && ratingIndex < 5) {
            spotCountByRating[ratingIndex]++
            // 假设每个景点的评论数等于commentCount
            totalCommentsByRating[ratingIndex] += spot.commentCount
            // 由于没有详细评论数据，我们将评论数平均分配到该评分段
            ratingDistribution[ratingIndex] += spot.commentCount
          }
        }
      } catch (e) {
        console.error('解析评论数据失败', e)
      }
    }
  })

  // 如果没有评论数据，使用景点评分作为备选
  if (ratingDistribution.every(count => count === 0)) {
    tableData.value.filter(item => item.rating > 0).forEach((item) => {
      const ratingIndex = Math.floor(item.rating) - 1
      if (ratingIndex >= 0 && ratingIndex < 5) {
        ratingDistribution[ratingIndex]++
      }
    })
  }

  const option = {
    tooltip: {
      trigger: 'item',
      formatter: function (params) {
        const index = params.dataIndex
        return `${params.name}: ${params.value}条评论<br/>景点数量: ${spotCountByRating[index] || 0}个<br/>占比: ${params.percent}%`
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true,
    },
    xAxis: {
      type: 'category',
      data: ['1星', '2星', '3星', '4星', '5星'],
    },
    yAxis: {
      type: 'value',
      name: '评论数量',
    },
    series: [
      {
        name: '评分分布',
        type: 'bar',
        data: ratingDistribution.map((value, index) => ({
          value,
          itemStyle: {
            color: getRatingColor(index + 1),
          },
        })),
        label: {
          show: true,
          position: 'top',
          formatter: '{c}条'
        }
      },
    ],
  }

  ratingChart.setOption(option)
}

// 根据评分获取颜色
const getRatingColor = (rating: number) => {
  const colors = ['#F56C6C', '#E6A23C', '#909399', '#67C23A', '#409EFF']
  return colors[rating - 1] || '#909399'
}

// 加载景点数据
const loadScenicSpotData = async () => {
  try {
    // 创建景点图层实例
    const attractionsLayer = new FeatureLayer({
      url: 'https://services5.arcgis.com/HfcuJ9RUSlysODB4/arcgis/rest/services/ScenicPoint/FeatureServer/0',
      outFields: ['OBJECTID', 'SpotName', 'SpotType', 'SpotIntroduction', 'UserJsonData'],
    })

    // 查询所有景点
    const query = attractionsLayer.createQuery()
    query.where = '1=1' // 查询所有记录
    query.outFields = ['*']

    const result = await attractionsLayer.queryFeatures(query)
    const features = result.features

    // 更新总数
    totalSpots.value = features.length

    // 处理景点数据
    const spots = features.map((feature) => {
      const attr = feature.attributes
      let visits = 0
      let rating = 0
      let commentCount = 0
      let lastUpdate = new Date().toLocaleString()

      // 解析UserJsonData获取真实评价数据
      if (attr.UserJsonData) {
        try {
          const userData = JSON.parse(attr.UserJsonData)
          if (userData.comments && userData.comments.length > 0) {
            commentCount = userData.comments.length
            visits = commentCount * 10 // 假设每条评论代表10个访问量

            // 使用存储的平均评分或计算平均评分
            if (userData.averageRating) {
              rating = userData.averageRating
            } else {
              const totalRating = userData.comments.reduce((sum, comment) => sum + comment.rating, 0)
              rating = totalRating / userData.comments.length
            }

            // 获取最新评论的时间作为最后更新时间
            const latestComment = userData.comments.reduce((latest, current) =>
              latest.timestamp > current.timestamp ? latest : current, userData.comments[0])
            if (latestComment && latestComment.timestamp) {
              const date = new Date(latestComment.timestamp)
              lastUpdate = date.toLocaleString()
            }
          }
        } catch (e) {
          console.error('解析用户数据失败', e)
        }
      }

      return {
        id: attr.OBJECTID,
        name: attr.SpotName || `景点 #${attr.OBJECTID}`,
        type: attr.SpotType || 'natural',
        description: attr.SpotIntroduction || '',
        UserJsonData: attr.UserJsonData || '',
        visits: visits,
        rating: parseFloat(rating.toFixed(1)),
        commentCount: commentCount,
        lastUpdate: lastUpdate,
      }
    })

    // 更新表格数据
    tableData.value = spots

    // 计算总访问量和平均评分
    totalVisits.value = spots.reduce((sum, spot) => sum + spot.visits, 0)
    const totalRating = spots.reduce((sum, spot) => sum + spot.rating, 0)
    avgRating.value = parseFloat((totalRating / (spots.filter(s => s.rating > 0).length || 1)).toFixed(1))

    // 初始化图表
    initCharts()
  } catch (error) {
    console.error('加载景点数据失败', error)
  }
}

// 初始化所有图表
const initCharts = () => {
  initSpotTypeChart()
  initVisitsChart()
  initPopularSpotsChart()
  initRatingChart()

  // 监听窗口大小变化，调整图表大小
  window.addEventListener('resize', handleResize)
}

// 处理窗口大小变化
const handleResize = () => {
  spotTypeChart?.resize()
  visitsChart?.resize()
  popularSpotsChart?.resize()
  ratingChart?.resize()
}

// 监听筛选条件变化
watch([searchKeyword, filterType], () => {
  currentPage.value = 1 // 重置到第一页
})

onMounted(() => {
  loadScenicSpotData()
})
</script>

<style scoped>
.statistics-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.page-title {
  margin-bottom: 24px;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
}

/* 数据概览卡片样式 */
.data-overview {
  margin-bottom: 24px;
}

.data-card {
  height: 120px;
  border-radius: 8px;
  overflow: hidden;
  transition: all 0.3s;

  .data-card:hover {
    transform: translateY(-5px);
    box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
  }
}

.card-content {
  height: 100%;
  display: flex;
  align-items: center;
  padding: 0 20px;
}

.card-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 20px;
  font-size: 24px;
}

.card-info {
  flex: 1;
}

.card-value {
  font-size: 28px;
  font-weight: 600;
  line-height: 1.2;
}

.card-label {
  font-size: 14px;
  color: #909399;
  margin-top: 5px;
}

/* 卡片颜色 */
.total-spots .card-icon {
  background-color: rgba(64, 158, 255, 0.1);
  color: #409eff;
}

.total-visits .card-icon {
  background-color: rgba(103, 194, 58, 0.1);
  color: #67c23a;
}

.avg-rating .card-icon {
  background-color: rgba(230, 162, 60, 0.1);
  color: #e6a23c;
}

/* 图表卡片样式 */
.chart-section {
  margin-bottom: 24px;
}

.chart-card {
  margin-bottom: 20px;
  border-radius: 8px;
}

.second-row {
  margin-top: 20px;
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-weight: 600;
}

.chart-container {
  height: 300px;
  width: 100%;
}

/* 表格卡片样式 */
.data-table-card {
  border-radius: 8px;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.search-input {
  width: 200px;
}

.filter-select {
  width: 150px;
}

.rating-display {
  display: flex;
  align-items: center;
  gap: 5px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .el-col {
    width: 100%;
    margin-bottom: 20px;
  }
}
</style>
